﻿using NewLife.Agent;
using NewLife.Threading;
using System.Threading;
using System;
using Microsoft.Extensions.Hosting;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;

namespace ReceiptPrint
{
    public class MyServices : ServiceBase
    {
        private CancellationTokenSource _source;
        public String[] Args { get; set; }
        private object _lock = new object();
        public MyServices()
        {
            ServiceName = "ReceiptPrintService";
            DisplayName = "小票打印服务";
            Description = "小票打印服务";
        }

        protected override void StopWork(String reason)
        {
            WriteLog("服务运行结束！{0}", reason);
            _source.Cancel();
            base.StopWork(reason);
        }

        protected override void StartWork(String reason)
        {
            WriteLog("服务运行开始……");
            _source = new CancellationTokenSource();
            var builder = CreateWebHostBuilder(Args).Build();
            builder.RunAsync(_source.Token);
            base.StartWork(reason);
        }

        public static IHostBuilder CreateWebHostBuilder(string[] args)
        {
            return
                  Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                  .ConfigureAppConfiguration((hostingContext, config) =>
                  {
                      config.AddInMemoryCollection(new Dictionary<string, string> { { "HostRoot", hostingContext.HostingEnvironment.ContentRootPath } });
                  })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseUrls("http://*:5000");
                    webBuilder.UseStartup<Startup>();
                });
        }
    }
}
